﻿using System;
using System.Linq;
using yiCommerce.Core.Domain.Customers;
using yiCommerce.Core.Domain.Securitys;
using yiCommerce.Service.Customers;

namespace yiCommerce.Service.Securitys
{
    public class PermissionService:IPermissionService
    {
        private ICustomerService _customerService;

        //public bool Authorize(PermissionRecord permission)
        //{
        //    return true;
        //}

        public PermissionService(ICustomerService customerService)
        {
            _customerService = customerService;
        }

        public bool Authorize(PermissionRecord permission, int customerId)
        {
            var customer = _customerService.GetCustomerById(customerId);

            return Authorize(permission.SystemName, customer);
        }

        private bool Authorize(string permissionRecordSystemName, Customer customer)
        {
            if (String.IsNullOrEmpty(permissionRecordSystemName))
                return false;

            var customerRoles = customer.CustomerRoles.Where(cr => cr.Active);
            foreach (var role in customerRoles)
                if (Authorize(permissionRecordSystemName, role))
                    //yes, we have such permission
                    return true;

            //no permission found
            return false;
        }


        protected virtual bool Authorize(string permissionRecordSystemName, CustomerRole customerRole)
        {
            if (String.IsNullOrEmpty(permissionRecordSystemName))
                return false;
            foreach (var permission1 in customerRole.PermissionRecords)
            {
                if (permission1.SystemName.Equals(permissionRecordSystemName, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }
            return false;

            //string key = string.Format(PERMISSIONS_ALLOWED_KEY, customerRole.Id, permissionRecordSystemName);
            //return _cacheManager.Get(key, () =>
            //{
            //    

            //    return false;
            //});
        }
    }
}